#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import sys
import traceback
from Ump.objs.sync.kbase import Base

class Sync(Base): 
    def __init__(self):
        super(Sync, self).__init__()

    def _ump_sync_cluster(self, cluster):
        '''同步一个集群的数据，return msgs， 如果msgs非空，说明有错误或异常产生'''
        msgs = []
        if cluster.hosts == [] :
            return ''
    
        #同步主机是否存在集群内
        try:
            self.cluster_manager.cluster_host_sync(cluster.id)
        except Exception, e:
            traceback.print_exc(file=sys.stderr)
            msg = 'Error cluster sync cluster: %s, %s'%(\
                    e, cluster)
            msgs.append(msg)
    
        #同步主机的状态，和资源使用情况
        results = []
        def cb(req, res):
            results.append([res])


        num_calls = [host.id for host in cluster.hosts if not host.deleted ]

        #同步主机信息和存储池
        num_threads = 10
        args = [
            [self.hom.host_sync, num_calls, num_threads, cb],
        ]
        self.utils.multi_exec(self._run_with_threadpool, args)
    
    def _ump_day_sync_cluster(self, cluster, is_create=False):
        msgs = []
        if cluster.hosts == []:
            return ''
        
        #同步主机的状态，和资源使用情况
        #hosts = [host for host in cluster.hosts if not host.deleted]
        #for host in hosts:
        #    try:
        #        self.hom.host_sync(host.id)
        #    except Exception, e:
        #        traceback.print_exc(file=sys.stderr)
        #        msg = 'Error cluster sync host: %s, %s, %s'%(e, cluster, host)
        #        msgs.append(msg)
        #    try:
        #        self.diskm.disk_light_sync(host.id)
        #    except Exception, e:
        #        traceback.print_exc(file=sys.stderr)
        #        msg = 'Error cluster sync host: %s, %s, %s'%(e, cluster, host)
        #        msgs.append(msg)

        self.poolm.pool_sync(cluster.id, is_create=is_create)
        self.vom.volume_sync(cluster.id, isDay=True, is_create=is_create)
        self.snapshotm.sync_snapshot(cluster.id)

        return msgs
